/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import Select from '../../common/Select'
import InputBox from '../../common/InputBox'
import PackTradeApply from './PackTradeApply'
import Relay from "react-relay";
import Createorder_StepOne from "./Createorder_StepOne";
import Createorder_DetailItem from "./Createorder_DetailItem";
import ReactKey from "../../util/ReactKey"
import AddExistStyleModal from "./AddExistStyleModal"
import Creatorder_StepThree from "./Createorder_StepThree";
import CalendarModal from "./CalendarModal";
import DetailUploadModal from "./DetailUploadModal";
import AddImgModal from "./AddImgModal";
import {Modal,Carousel} from 'antd';
import AddPartBModal from "./AddPartBModal";
import SaveOrderMutation from "./mutation/SaveOrderMutation"
import TotalCount from "./TotalCount"
import TotalCountChinese from "./TotalCountChinese"
import getEnOrderTypeMutation from "./mutation/GetEnOrderTypeMutation"
/*信息列表*/
export default class Createorder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num: 0,
            goods: [],
            goodsremark: [],
            showitembottom: false,
            instructions: [],
            orderId:"",
            ordertype_num:"",
        };

        this.goods = [{}, {}, {}];
        this.goodsremark = [{}, {}, {}];
        this.showitembottom = false;
        this.ordertype_num = "";
        this.instructions = [];
        this.ordertype = [
            {text:'请选择订单类型',value:'0'}
            /*{text: '成衣订单', value: '0'},
            {text: '面料订单', value: '1'},
            {text: '纱线订单', value: '2'},
            {text: '印染订单', value: '3'},
           */
        ];
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.permissionId = sessionStorage.getItem('permissionId');
        this.entype = sessionStorage.getItem('entype');
        this.additemlist = this.additemlist.bind(this);
        this.delteitem = this.delteitem.bind(this);
        this.addremarkitemlist = this.addremarkitemlist.bind(this);
        this.deremarkteitem = this.deremarkteitem.bind(this);
    }


    componentWillMount() {
        this.state.num = this.goods.length;
        this.setState({
            goods: this.goods,
            goodsremark: this.goodsremark
        },()=>{
            /*获取当前企业可发布订单类型*/

        });
        Relay.Store.commitUpdate(
            new getEnOrderTypeMutation({
                enId :this.enterpriseId,
            }),
            {
                onFailure: () => {
                    // console.log("请求失败-乙方企业")
                },
                onSuccess: (response) => {
                    let errorCode = response.getEnOrderType.getEnOrderType.errorCode;
                    let ordertype = [];
                    if(errorCode=="0"){
                        ordertype = response.getEnOrderType.getEnOrderType.enOrderType.ordertype;
                        ordertype = JSON.parse(ordertype);
                        ordertype.map((item,index)=>{
                            this.ordertype.push(item)
                        });
                        this.setState({
                            ordertype:this.ordertype
                        });
                        // console.log(this.ordertype);
                    }
                }
            }
        )

    }
    /*选择订单类型*/
    chooseordertype(id){
        this.ordertype_num = id;
    }

    handleclick() {
    }

    showimgmodal(index){
        this.refs.addimg.setState({
            visible:true,
            index:index
        });
    }

    setgoodsimg(url,index){
        if(!url){
            Modal.warning({
                title: '图片',
                content: '请选择图片',
            });
            return;
        }
        if(index+1){
            let goods = this.state.goods
            goods[index].url = url;
            this.setState({
                goods:goods
            });
        }else{
        }
        this.refs.addimg.setState({
            visible:false
        });
    }
    additem() {
        return this.state.goods.map((context, index)=> {
            let isshow = true
            return (
                <Createorder_DetailItem context={context} index={index} key={ReactKey.key}
                                        additemlist={this.additemlist}
                                        delteitem={this.delteitem}
                                        totallenght={this.state.goods.length}
                                        repalceitem={this.repalceitem.bind(this)}
                                        isshow={isshow}
                                        showimgmodal = {this.showimgmodal.bind(this)}
                                        ref={'creatorderditem'+index}
                                        setcountcallback = {this.setcountcallback.bind(this)}
                                        />
            );
        });
    }


    repalceitem(context, index) {
        let goods = this.state.goods;
        goods.splice(index, 1, context);
        this.setState({
            goods: goods
        });
    }

    showitemall() {
        this.setState({
            showitembottom: true
        });
    }

    additembottom() {
        if (this.state.showitembottom || this.state.goods.length < 5) {
            return (
                null
            );

        } else {
            return (
                <div onClick={this.showitemall.bind(this)}>
                    是否显示全部
                </div>
            );
        }

    }

    addpurchasetype() {
        if (this.entype == "6") {//贸易商
            return (
                <p style={{width: 1114, height: 58, paddingLeft: "60px", lineHeight: "58px", background: "#f4fafa", border: "1px solid #cacaca",position:"relative",marginBottom:"20px",position:"relative"}}>
                    <span
                        style={{position:"absolute",left:"50px",top:"20px",color:"red",display:"block",fontSize:"16px"}}>*</span>
                    采购商品：
                    <span
                        style={{display:"block",marginLeft:"20px",marginTop:"20px",width:119,height:25,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3",position:"absolute",left:"100px",top:"0px"}}>
                        成衣
                    </span>
                </p>
            );

        } else {
            // console.log(this.state.ordertype);
            return (
                <p style={{width: 1114, height: 58, paddingLeft: "60px", lineHeight: "58px", background: "#f4fafa", border: "1px solid #cacaca",position:"relative",marginBottom:"20px"}}>
                    <span
                        style={{position:"absolute",left:"50px",top:"25px",color:"red",display:"block",fontSize:"16px"}}>*</span>
                    采购商品：
                    <Select oArr={this.ordertype} onselectchose={this.chooseordertype.bind(this)} ref={"_ordertype"}
                            style={{marginLeft:"20px",marginTop:"20px",width:119,height:25,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3"}}/>
                </p>
            );
        }
    }

    addstepone() {
        return (
            <Createorder_StepOne ispartA={this.ispartA} enterpriseId={this.enterpriseId} ref={'stepone'}/>
        );
    }

    addStepThree() {
        return this.state.goodsremark.map((context, index)=> {
            return (
                <Creatorder_StepThree key={ReactKey.key} index={index} context={context}
                                      addremarkitemlist={this.addremarkitemlist}
                                      deremarkteitem={this.deremarkteitem}
                                      totallenght={this.state.goodsremark.length}
                                      />
            );
        });
    }

    delqiniufile(item, fileKye) {
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: fileKye
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        Util.removedarrayitem(this.instructions, item);
                        this.setState({
                            instructions: this.instructions
                        });
                    }
                }
            }
        )
    }

    addinstructions() {
        if (this.instructions.length >= 5) {
            alert('不能超过5个');
            return
        }
        this.refs.deup.setState({
            visible: true
        });
    }

    addpact(name, hash, url, fileKey) {
        this.instructions.push({"name": name, "hash": hash, "url": url, "fileKey": fileKey});
        this.setState({
            instructions: this.instructions
        });
    }


    attach() {
        if (this.instructions) {

        }
        return this.state.instructions.map((item, index)=> {
            return (
                <PackTradeApply key={index} key={ReactKey.key} item={item} delqiniufile={this.delqiniufile.bind(this)}/>
            );

        })
    }

    showlibrary() {

        this.refs.addesm.setState({
            visible: true
        });
    }


    addModalfromlist(orders) {
        let goods = this.state.goods;
        let tgoods = goods.concat(orders);
        this.setState({
            goods: tgoods
        });
        this.refs.addesm.setState({
            visible: false,
        });
    }

    additemlist() {
        let goods = this.state.goods;
        goods.push({});
        this.setState({
            goods: goods
        });

    }

    delteitem(index) {
        let goods = this.state.goods;
        goods.splice(index, 1);
        this.setState({
            goods: goods
        });
    }

    addremarkitemlist() {
        let goodsremark = this.state.goodsremark;
        goodsremark.push({});
        this.setState({
            goodsremark: goodsremark
        });

    }

    deremarkteitem(index) {
        let goodsremark = this.state.goodsremark;
        goodsremark.splice(index, 1);
        this.setState({
            goodsremark: goodsremark
        });
    }

    setcountcallback(){
        let total = 0;
        let totalmoney=0;
        this.state.goods.map((context,index)=>{
           let quantity = this.refs['creatorderditem'+index].state.context.quantity;
           let price = this.refs['creatorderditem'+index].state.context.price;
            if(quantity){
                total = total+Number(quantity);
            }
            if(quantity&&price){
                let temptotal = Number(quantity)*Number(price)
                if(!isNaN(totalmoney)){
                    totalmoney = totalmoney+temptotal
                }
            }
        });
        this.refs.totalcount.setState({
            quantity:total,
            totalprice:totalmoney
        });
        this.refs.totalcountchinese.setState({
            count:totalmoney,
        });
    }

    addfrom(){
        return(
            <div className="order_form_total_div">
                <span className="order_form_top_span">
                </span>
                <table className="order_form_table">
                    <thead>
                    <tr className="order_from_tr">
                        <td className="order_frorm_td order_from_td_num "/>
                        <td className="order_frorm_td order_from_td_snum">款号</td>
                        <td className="order_frorm_td order_from_td_cnum">品名</td>
                        <td className="order_frorm_td order_from_td_describe">描述</td>
                        <td className="order_frorm_td order_from_td_img">花型图片</td>
                        <td className="order_frorm_td order_from_td_size">规格/尺码</td>
                        <td className="order_frorm_td order_from_td_monad">单位</td>
                        <td className="order_frorm_td order_from_td_ucost">单价</td>
                        <td className="order_frorm_td order_from_td_pnum">数量</td>
                        <td className="order_frorm_td order_from_td_moeny">金额</td>
                        <td className="order_frorm_td order_from_td_delandadd"/>
                    </tr>
                    </thead>
                    {
                        this.additem()
                    }

                    <TotalCount ref={'totalcount'}/>

                    <TotalCountChinese ref={"totalcountchinese"}/>

                </table>

            </div>
        );
    }

    creatorder(){
        let object = [{name:1}];
        let objects = [{orderId:1}];
        let stest = JSON.stringify(object);
        let stests = JSON.stringify(objects);
        this.setState({
            ordertype_num:this.ordertype_num
        },()=>{
            Relay.Store.commitUpdate(
                new SaveOrderMutation({
                    parentId:'',
                    createUser:26,
                    enId:2,
                    account:300,
                    payAccount:2000,
                    status:0,
                    orderType:0,
                    partA:this.enterpriseId,
                    partAName:'界安防',
                    partAAddress:"花梨坎",
                    partAUserId:26,
                    partAUserName:'dalao',
                    rmark:'没',
                    contractId:'adaxsfg',
                    goodsInfo:stest,
                    traderUrl1:'',
                    traderUrl2:'',
                    traderUrl3:'',
                    traderUrl4:'',
                    traderUrl5:'',
                    contractUrl1:'',
                    contractUrl2:'',
                    contractUrl3:'',
                    contractUrl4:'',
                    contractUrl5:'',
                    deliverRequest:stests
                }),
                {
                    onFailure: () => {

                    },
                    onSuccess: (response) => {
                        let errorCode = response.saveOrder.saveOrder.errorCode;
                        if(errorCode == 0){
                            let list = this.refs.stepone.state.enterpriseList;
                            this.refs.addpartb.setState({
                                visible:true,
                                enterpriseList:list,
                                orderId:response.saveOrder.saveOrder.order.oid
                            });
                        }
                    }
                }
            )
        });

    }

    deletorder(){

    }

    render() {
        return (
            <div className="createorder_box"
                 style={{width: 1233, minHeight: 875, background: "#f5f5f5", paddingTop: "20px",paddingBottom:"30px"}}>
                <p style={{height: 44, lineHeight: "44px"}}>订单管理>新建订单</p>
                <div style={{width: 1233, minHeight: 500, background: "#fff", padding: "10px 30px 0 30px"}}>
                    {
                        this.addpurchasetype()
                    }

                    <div
                        style={{width:1174,minHeight:500,border:"1px dashed #ccc",borderRadius:"5px",position:"relative",paddingBottom:"30px"}}>
                        {
                            this.addstepone()
                        }
                        <p style={{color: "#36b3b3", height: 44, lineHeight: "44px", fontSize: "16px",marginTop:"27px",paddingLeft:"40px",position:"relative",cursor:'pointer'}}>
                            第二步：添加商品&服务明细
                            <span
                                style={{width:738,height:1,background:"#cde0ee",display:"block",position:"absolute",top:"22px",left:"260px"}}/>
                            <span
                                style={{color: "#36b3b3", height: 44, lineHeight: "44px", fontSize: "12px",marginTop:"27px",marginLeft:"780px",position:"relative"}}
                                onClick={this.showlibrary.bind(this)}>+从商品库选择</span>
                        </p>
                        {
                            this.addfrom()
                        }


                        <p style={{color: "#36b3b3", height: 44, lineHeight: "44px", fontSize: "16px",marginTop:"27px",paddingLeft:"40px",position:"relative"}}>
                            第三步：添加交货要求
                            <span
                                style={{width:937,height:1,background:"#cde0ee",display:"block",position:"absolute",top:"22px",left:"222px"}}/>
                        </p>

                        <table className="order_form_table">
                            <thead>
                            <tr className="order_from_tr">
                                <td className="order_frorm_td order_frorm_td_three_time">交货时间</td>
                                <td className="order_frorm_td order_frorm_td_three_num">数量</td>
                                <td className="order_frorm_td order_frorm_td_three_remark">备注</td>
                                <td className="order_frorm_td order_frorm_td_three_adddetel"/>
                            </tr>
                            </thead>
                            {
                                this.addStepThree()
                            }
                        </table>
                        <p style={{color: "#36b3b3", height: 44, lineHeight: "44px", fontSize: "16px",marginTop:"27px",paddingLeft:"40px",position:"relative"}}>
                            第四步：上传合同附件
                            <span
                                style={{width:937,height:1,background:"#cde0ee",display:"block",position:"absolute",top:"22px",left:"222px"}}/>
                        </p>

                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>
                            <span
                                style={{width: 110, display: "block", float: "left",marginLeft:0,marginTop:6,marginRight:24}}>合同贸易附件：</span>
                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span style={{height:30,width:40,marginLeft:160,cursor:'pointer'}}
                              onClick={this.addinstructions.bind(this)}>添加</span>
                        <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                            <span style={{position: "absolute", top: "0px", left: "42px",fontSize:"14px"}}>备注：</span>
                            <InputBox multiline space={"20"}
                                      style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}}/>
                        </div>

                        <button className="order_main_creat_button" onClick={this.creatorder.bind(this,this.imageUrl,this.state.index)}>
                            创建</button>
                        <button className="order_main_delet_button" onClick={this.deletorder.bind(this)}>删除</button>

                        <div className="order_main_creat_div"></div>
                    </div>
                </div>

                <AddExistStyleModal ref={'addesm'} addModalfromlist={this.addModalfromlist.bind(this)}/>
                <DetailUploadModal ref={'deup'} addpact={this.addpact.bind(this)} mid={'creat'}/>
                <CalendarModal ref={'calendar'}/>
                <AddImgModal ref={'addimg'} setgoodsimg={this.setgoodsimg.bind(this)} key={ReactKey.key}/>
                <AddPartBModal ref={'addpartb'} key={ReactKey.key} enterpriseId={this.enterpriseId} entype={this.entype} ordertype_num={this.state.ordertype_num}/>
            </div>

        )
    }
}
